package com.yb.guigu.pick.security.matcher;

import com.yb.guigu.pick.security.bean.WhiteListProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/20 11:25
 * FileName: UrlIgnoreRequestMatcher
 * Description:
 */

@Slf4j
public class PermitAllRequestMatcher implements RequestMatcher, InitializingBean {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    final WhiteListProperties whiteListProperties;

    @Value("${spring.application.name}")
    private String appName;

    public PermitAllRequestMatcher(WhiteListProperties whiteListProperties){
        this.whiteListProperties=whiteListProperties;
    }

    @Override
    public boolean matches(HttpServletRequest request) {

        String servletPath = request.getServletPath();

        log.info("servletPath {}",servletPath);

        List<String> urls = whiteListProperties.getUrls();

        boolean result = urls.stream().anyMatch(pattern -> antPathMatcher.match(pattern, servletPath));

        log.info("match result:{}",result);

        return result;
    }

    @Override
    public void afterPropertiesSet() {
        log.info("secure application 【{}】 with permitAllList :{}",appName,whiteListProperties.getUrls());
    }
}
